import pathToRegexp from 'path-to-regexp'
import api from 'api'

const {
    queryAdminList,
    saveAdmin,
    updateAdmin,
    deleteAdmin,
    queryRole
} = api

export default {
  namespace: 'admin',

  state: {
    list: [],
    pagination: {
      current: 1,
      total: 0,
      pageSize: 10,
    },

    roleList: [],

    currentItem: {},
    modalVisible: false,
    modalType: 'create'
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if (pathToRegexp('/admin/list').exec(pathname)) {
          dispatch({ type: 'query' })
          dispatch({ type: 'queryRole' })
        }
      })
    },
  },

  effects: {
    *query({ payload = {} }, { call, put, select }) {
      const data = yield call(queryAdminList, payload)

      if (data && data.data) {
        const result = data.data
        yield put({
          type: 'querySuccess',
          payload: {
            list: result.data || [],
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: result.total,
            },
          },
        })
      }
    },
    *create({ payload }, { call, put }) {
      const data = yield call(saveAdmin, payload)
      console.log(data,61)
      if (data.code === 200) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      const id = yield select(({ admin }) => admin.currentItem.id)
      const newUser = { ...payload, id }
      const data = yield call(updateAdmin, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *delete({ payload }, { call, put }) {
      const data = yield call(deleteAdmin, { id: payload })
      if (data.success) {
        return data
      } else {
        throw data
      }
    },

    *queryRole({ payload = {} }, { call, put }) {
      const data = yield call(queryRole, payload);
      if(data.success) {
        const result = data.data;
        yield put({
          type: 'setState',
          payload: {
            roleList: result || [],
          }
        })
      } else {
        throw data
      }
    },
  },

  reducers: {
    setState(state, action) {
      return {
        ...state,
        ...action.payload,
      }
    },

    querySuccess(state, { payload }) {
      const { list, pagination } = payload
      return {
        ...state,
        list,
        pagination: {
          ...state.pagination,
          ...pagination,
        },
      }
    },

    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
}
